import 'package:flutter/material.dart';
import 'package:znmm/config/app_gaps.dart';

//------------------上拉加载更多
class InfiniteListView extends StatefulWidget {
  final Future<void> Function()? onLoadMore; // 加载更多数据的回调，可选
  final List items; // 数据列表
  final Widget Function(BuildContext, int) itemBuilder; // 每个列表项的构建逻辑
  final bool hasMore; // 是否还有更多数据
  final Widget? noMoreWidget; // 没有更多数据时的自定义显示内容
  final bool bIsHaveLine;

  const InfiniteListView(
      {Key? key,
      this.onLoadMore, // 默认可空
      required this.items,
      required this.itemBuilder,
      this.hasMore = true, // 默认还有更多数据
      this.noMoreWidget,
      this.bIsHaveLine = false})
      : super(key: key);

  @override
  // ignore: library_private_types_in_public_api
  _InfiniteListViewState createState() => _InfiniteListViewState();
}

class _InfiniteListViewState extends State<InfiniteListView> {
  final ScrollController _scrollController = ScrollController();
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
              _scrollController.position.maxScrollExtent &&
          widget.hasMore &&
          !_isLoading) {
        _loadMoreData();
      }
    });
  }

  Future<void> _loadMoreData() async {
    if (widget.onLoadMore == null) return; // 如果未传递加载回调，直接返回

    setState(() {
      _isLoading = true;
    });

    await widget.onLoadMore?.call();

    setState(() {
      _isLoading = false;
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      separatorBuilder: (_, __) {
        return widget.bIsHaveLine
            ? Container(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: AppGaps.hLine,
              )
            : Container();
      },
      cacheExtent: 500,
      controller: _scrollController,
      itemCount: widget.items.length + 1, // 加一是为了显示加载指示器或“没有更多数据”

      itemBuilder: (context, index) {
        if (index == widget.items.length) {
          // 最后一项：加载指示器或没有更多数据的提示
          if (widget.hasMore) {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: _isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : const SizedBox.shrink(),
            );
          } else {
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: widget.noMoreWidget ?? const Center(child: Text('没有更多数据')),
            );
          }
        }
        return widget.itemBuilder(context, index);
      },
    );
  }
}


/*

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'infinite_list_view.dart';

class SendEmailListView extends StatefulWidget {
  const SendEmailListView({super.key});

  @override
  State<SendEmailListView> createState() => _SendEmailListViewState();
}

class _SendEmailListViewState extends State<SendEmailListView> {
  List<String> _items = List.generate(20, (index) => 'Item #$index');
  bool _hasMore = true;

  Future<void> _loadMoreData() async {
    await Future.delayed(Duration(seconds: 2));
    if (_items.length >= 50) {
      setState(() {
        _hasMore = false; // 没有更多数据
      });
    } else {
      setState(() {
        _items.addAll(
            List.generate(20, (index) => 'Item #${_items.length + index}'));
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('上拉刷新列表')),
      body: InfiniteListView(
        items: _items,
        onLoadMore: _hasMore ? _loadMoreData : null, // 根据是否有更多数据决定是否传递回调
        hasMore: _hasMore, // 是否还有更多数据
        noMoreWidget: Center(
          child: Text(
            '已经到底了~',
            style: TextStyle(color: Colors.grey),
          ),
        ),
        itemBuilder: (context, index) {
          return ListTile(
            title: Text(_items[index]),
          );
        },
      ),
    );
  }
}


*/